package com.unicloud.medical.oss.core.annotation;

import com.unicloud.medical.oss.common.enums.ErrorEnum;
import com.unisound.medical.common.exception.BusinessException;
import com.unisound.medical.common.exception.ExceptionMessage;
import com.unisound.medical.common.model.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Slf4j
@Aspect
public class ExceptionInterceptorAspect {
    @Pointcut("@annotation(com.unicloud.medical.oss.core.annotation.ExceptionInterceptor)")
    public void exceptionInterceptorPointcut() {
    }

    /**
     * 此切面只处理 ResultDTO类型返回值的异常
     * @param joinPoint
     * @param exceptionInterceptor
     */
    @Around("exceptionInterceptorPointcut() && @annotation(exceptionInterceptor)")
    public Object execute(ProceedingJoinPoint joinPoint, ExceptionInterceptor exceptionInterceptor) throws Throwable {
        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            ExceptionMessage errorMessage = errorMessage(e);
            return ResultDTO.fail(errorMessage.getErrorCode(), errorMessage.getErrorMessage());
        }
    }

    private ExceptionMessage errorMessage(Exception e) {
        if (e instanceof BusinessException) {
            return ((BusinessException) e).getExceptionMessage();
        }

        log.error("errorMessage. cause={}", e);
        ErrorEnum errorEnum = ErrorEnum.SYSTEM_ERROR;
        return new ExceptionMessage(errorEnum.getErrCode(), errorEnum.getErrMsg());
    }
}
